/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.reddys.rad.inventory.controller;

import com.reddys.rad.inventory.db.PurchaseOrderDetails;
import com.reddys.rad.inventory.db.Sale;
import com.reddys.rad.inventory.db.SaleDetails;
import com.reddys.rad.inventory.db.SalesReturn;
import com.reddys.rad.inventory.db.Vendor;
import com.reddys.rad.inventory.service.PurchaseOrderService;
import com.reddys.rad.inventory.service.SalesReturnService;
import com.reddys.rad.inventory.service.SalesService;
import com.reddys.rad.inventory.utils.EditingCell;
import com.reddys.rad.inventory.utils.EditingCellForSaleReturn;
import com.reddys.rad.inventory.utils.Utilities;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.Callback;

/**
 * FXML Controller class
 *
 * @author REDDYS
 */
public class SalesReturnController implements Initializable {

    /**
     * Initializes the controller class.
     */
    private  ObservableList salesList =  FXCollections.observableArrayList();
    private  ObservableList saleIdList =  FXCollections.observableArrayList();
    private  ObservableList tableList =  FXCollections.observableArrayList();
    private  List<SaleDetails> saleDetailsList =  new ArrayList<SaleDetails>();
            ObservableList list2= FXCollections.observableArrayList();
    private final ObservableList<PurchaseOrderDetails> data =  FXCollections.observableArrayList();
    
    @FXML
    private TextField saleReturnId;
    @FXML
    private TextField saleReturnDesc;
    @FXML
    private ComboBox saleId;
    @FXML
    private TextField saleDate;
    @FXML
    private TextField saleReturnDate;
    @FXML
    private TextField customerId;
    @FXML
    private TextArea customerDetails;
    @FXML
    private TableView detailsTable;
    @FXML
    private TableColumn colProductCat;
      @FXML
    private TableColumn colProductId;
      @FXML
    private TableColumn colProductName;
      @FXML
    private TableColumn colItemCode;
      @FXML
    private TableColumn colBatchCode;
      @FXML
    private TableColumn colProductUOM;
      @FXML
    private TableColumn colQuantity;
    @FXML
    private TableColumn colQuantityReturned;
    @FXML
    private TableColumn colUnitPrice;
    @FXML
    private TableColumn colVat;
    @FXML
    private TableColumn colTax;
    @FXML
    private TableColumn colDiscount;
      @FXML
    private TableColumn colNetPrice;                        
            
    
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        salesList = getSalesReturnService().getSalesList();
        for(int i=0;i<salesList.size();i++){
           Sale sale =(Sale)salesList.get(i);
           saleIdList.add(sale.getSaleId());
        }
        saleId.getItems().addAll(saleIdList);
        loadTableColumns(detailsTable);
        addEmptyRows();
        saleId.focusedProperty().addListener(new ChangeListener<Boolean>() {
            @Override
            public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) {
                     String txtSaleId = (String) saleId.getSelectionModel().getSelectedItem();
                     if(txtSaleId!=null){
                          populateDetailsTable(txtSaleId);
                     }else{
                     }
                    
                
            }
        });
    }    
    
        public SalesReturnService getSalesReturnService(){
        SalesReturnService salesReturnService = new SalesReturnService();
        return salesReturnService;
    }
        
        public void populateDetailsTable(String saleId){
        
            Sale sale = new Sale();
            for(int i=0;i<salesList.size();i++){
                sale=(Sale)salesList.get(i);
                if(sale.getSaleId().equals(saleId)){
                    saleDetailsList = getSalesReturnService().getSaleDetailsList(sale);
                }
           }
            detailsTable.getItems().clear();

            for(SaleDetails s :saleDetailsList){
                ObservableList list1= FXCollections.observableArrayList();
                list1.add(s.getProductCategory());
                list1.add(s.getProductId());
                list1.add(s.getProductDescription());
                list1.add(s.getItemCode());
                list1.add(s.getBatchCode());
                list1.add(s.getQuantity());
                list1.add(s.getUom());
                list1.add(s.getUnitPrice());
                list1.add(s.getVat());
                list1.add(s.getTax());
                list1.add(s.getDiscount());
                list1.add(s.getNetPrice());
                list1.add(s.getSaleDetailId());
               list2.add(list1);
                        
            }
            detailsTable.setItems(list2);
        colProductCat.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( cdf.getValue().get(0)!=null?cdf.getValue().get(0).toString():"");
            }
        });
        colProductId.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( cdf.getValue().get(1)!=null?cdf.getValue().get(1).toString():"");
            }
           

           
        });
        
        colProductName.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( cdf.getValue().get(2)!=null?cdf.getValue().get(2).toString():"");
            }
           

           
        });
        
        colItemCode.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty(cdf.getValue().get(3)!=null?cdf.getValue().get(3).toString():"");
            }
           

           
        });
        
       colBatchCode.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( cdf.getValue().get(4)!=null?cdf.getValue().get(4).toString():"");
            }
            
           

           
        });
       
        colQuantity.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( cdf.getValue().get(5)!=null?String.valueOf(cdf.getValue().get(5)):"");
            }
           

           
        });
        
        
        colProductUOM.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( cdf.getValue().get(6)!=null?cdf.getValue().get(6).toString():"");
            }
           

           
        });
        
        colUnitPrice.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( cdf.getValue().get(7)!=null?String.valueOf(cdf.getValue().get(7)):"");
            }
           

           
        });
        
        colVat.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( cdf.getValue().get(8)!=null?String.valueOf(cdf.getValue().get(8)):"");
            }
           

           
        });
        
        colTax.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( cdf.getValue().get(9)!=null?String.valueOf(cdf.getValue().get(9)):"");
            }
           

           
        });
        
        colDiscount.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( cdf.getValue().get(10)!=null?String.valueOf(cdf.getValue().get(10)):"");
            }
           

           
        });
        
        colNetPrice.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
              return new SimpleStringProperty( cdf.getValue().get(11)!=null?String.valueOf(cdf.getValue().get(11)):"");
            }
           

           
        });
        detailsTable.setEditable(true);
      Callback<TableColumn, TableCell> cellFactory =
              new Callback<TableColumn, TableCell>() {
                  public TableCell call(TableColumn p) {
                      return new EditingCell();
                  }
              };
         colQuantityReturned.setCellFactory(new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCellForSaleReturn("Returned");
                 }
             });
        }
        
        
            @FXML
    private void addEmptyRows() {
        for(int i=0;i<10;i++){
         data.add(new PurchaseOrderDetails());
        }
    }
       private void loadTableColumns(TableView tableView) {
      
        tableView.setEditable(true);
        colProductCat = new TableColumn("Product Category");
        colProductCat.setMinWidth(150);
        colProductCat.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("colProductCat"));
/*        productCategory.setOnEditCommit(
                new EventHandler<TableColumn.CellEditEvent<PurchaseOrderDetails, String>>() {
                     
                    @Override 
                    public void handle(TableColumn.CellEditEvent<PurchaseOrderDetails, String> t) {
                         System.out.println(t);
                        System.out.println("before Setting"+((PurchaseOrderDetails)t.getTableView().getItems().get(t.getTablePosition().getRow())).getProductId());
                        ((PurchaseOrderDetails)t.getTableView().getItems().get(
                                t.getTablePosition().getRow())).setProductId(t.getNewValue());
                        System.out.println("after Setting"+((PurchaseOrderDetails)t.getTableView().getItems().get(t.getTablePosition().getRow())).getProductId());
                    }
                });
 */
        colProductId = new TableColumn("Product ID");
        colProductId.setMinWidth(100);
        colProductId.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("colProductId"));
        colProductId.setCellFactory(new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                     
                    return new EditingCell("ProductID");
                 }
             });
 /*       productID.setOnEditCommit(
            new EventHandler<CellEditEvent<PurchaseOrderDetails, String>>() {
                @Override
                public void handle(CellEditEvent<PurchaseOrderDetails, String> t) {
                    ((PurchaseOrderDetails) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())
                        ).setProductId(t.getNewValue());
                }
             }
        );
 */
        colProductName = new TableColumn("Product Name");
        colProductName.setMinWidth(100);
        colProductName.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("colProductName"));
        
       // productName.setCellFactory(cellFactory);
        
        colItemCode = new TableColumn("Item Code");
       colItemCode.setMinWidth(100);
        colItemCode.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("colItemCode"));
        //itemCode.setCellFactory(cellFactory);
        
       colBatchCode = new TableColumn("Batch Code");
        colBatchCode.setMinWidth(100);
        colBatchCode.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("colbatchCode"));
      
          colProductUOM = new TableColumn("UOM");
        colProductUOM.setMinWidth(100);
        colProductUOM.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("colProductUOM"));
        
          colQuantity = new TableColumn("Qty Received");
        colQuantity.setMinWidth(100);
        colQuantity.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("colQuantity"));
        
  colQuantityReturned = new TableColumn("Qty Returned");
    colQuantityReturned.setMinWidth(100);
        colQuantityReturned.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("colQuantityReturned"));
                colQuantityReturned.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCellForSaleReturn();
                 }
             });
         colUnitPrice = new TableColumn("Unit Price");
      colUnitPrice.setMinWidth(100);
        colUnitPrice.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("colUnitPrice"));
        
     colVat = new TableColumn("VAT");
        colVat.setMinWidth(100);
        colVat.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("colVat"));
        
         colTax = new TableColumn("TAX");
       colTax.setMinWidth(100);
        colTax.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("colTax"));
        
        
        colDiscount = new TableColumn("Discount");
      colDiscount.setMinWidth(100);
        colDiscount.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("colDiscount"));
        
        
         colNetPrice = new TableColumn("Net Price");
        colNetPrice.setMinWidth(100);
        colNetPrice.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("colNetPrice"));
        
        
        tableView.getColumns().clear();
        tableView.getColumns().addAll(colProductCat, colProductId, colProductName,colItemCode,colBatchCode,colProductUOM,colQuantity,colQuantityReturned,colUnitPrice,colVat,colTax,colDiscount,colNetPrice);
        tableView.setItems(data);
        
    }
  private boolean validateSave() {
    /*    if(Utilities.isNull(vendor.getText())){
            return false;
        }*/
      System.out.println("desc"+saleReturnDesc.getText()+"aaa");
      if(saleReturnDesc.getText()==null && saleReturnDesc.getText()==""){
          Utilities.createDialog("Please enter sale return description");
          return false;
      }
      String txtSaleId = (String) saleId.getSelectionModel().getSelectedItem();
      if(txtSaleId==null){
          Utilities.createDialog("Please select sale id");
          return false;
      }
      
     if(customerDetails.getText()==null && customerDetails.getText()==""){
          Utilities.createDialog("Please enter customer details");
          return false;
      }
        return true;
    }
  @FXML
  private void save(){
      try{
          if(validateSave()){
      SalesReturn saleRet = new SalesReturn();
      tableList = detailsTable.getItems();
      for(int i=0;i<tableList.size();i++){
          String productId = (String)((ObservableList)tableList.get(i)).get(1);
          String saleDetailId = (String)((ObservableList)tableList.get(i)).get(12);
          Double received = (Double)((ObservableList)tableList.get(i)).get(5);
          Double returned = (Double)((ObservableList)tableList.get(i)).get(7);
          if(returned!=null && returned>=0 && returned<received){
            saleRet.setSaleReturnDescription(saleReturnDesc.getText());
            //saleRet.setSaleReturnDate();
            saleRet.setSaleId((String) saleId.getSelectionModel().getSelectedItem());
            saleRet.setCustomerId(customerId.getText());
            saleRet.setCustomerDetails(customerDetails.getText());
            getSalesReturnService().saveHeader(saleRet);

            SaleDetails detail = getSalesReturnService().getSaleDetails(saleDetailId);
            detail.setQuantityReturned(returned);
            getSalesReturnService().updateSaleDetails(detail);
            Utilities.createDialog("Transaction Completed Successfully");     
          }else{
              Utilities.createDialog("Enter valid quantity returned and ensure less than received quantity");
          }
      }
      }
      }catch(Exception e){
          e.printStackTrace();;
          Utilities.createDialog("Transaction Failed");
      }
      
      
  }

            
}
